$.views.converters({
	fgoodsStatus : function(value) {
		if(!value){
			return "";
		}
		for(index in stats_goodsStatus){
			var goodsStatus = stats_goodsStatus[index];
			if(goodsStatus.dictCode == value){
				return goodsStatus.dictName;
			}
		}
		return  "未知类型("+value+")";
	},

	fapplyStatus : function(value){
		if(!value){
			return "";
		}
		for(index in stats_approves){
			var approves = stats_approves[index];
			if(approves.dictCode == value){
				return approves.dictName;
			}
		}
		return  "未知类型("+value+")";
	},
	fmoneyUnit : function(value){
		if(!value){
			return "";
		}
		for(index in stats_currencys){
			var currencys = stats_currencys[index];
			if(currencys.dictCode == value){
				return currencys.dictName;
			}
		}
		return  "未知类型("+value+")";
	}
});
var goodsStatsCtrl  = new XFApp.client();
XFApp.client.prototype.goodsStats = {
	successCode : "10000",
	page : null,
	hisPage : null,
	hgPage : null,
	hisId : 0,
	cusPage : null,
	currentPageNo:0,
	urlItems : {
		queryHgGoodsByPageURL : basePath + "/nt/packageForstats/goodsRecord/queryHgGPage",
		queryByPageURL : basePath+"/nt/packageForstats/goodsStats/queryPage",
		delGoodsRUL : basePath +"/nt/packageForstats/goodsRecord/delGoods",
		queryCustomerByPageURL : basePath + "/nt/packageForstats/goodsRecord/queryCusPage",
		queryByHisPageURL : basePath + "/nt/packageForstats/goodsStats/queryHistoryPage",
		importDataURL:basePath+"/nt/packageForstats/goodsRecord/importGoods",//导入备案 @ps
		downLoadURL:basePath+"/nt/packageForstats/goodsRecord/downloadTemplate",//下载模板 @ps
		downLoadURLWithRealPath:basePath+"/nt/newIm/downloadTemplate",//下载模板 @ps
		exportErrorGoodsExcel : basePath+"/nt/newIm/exportErrorGoodsExcel",  //下载未成功备案的商品数据
		batchSubmitGoodsUrl: basePath +"/nt/packageForstats/goodsRecord/batchSubmitGoods"//提交备案url

	},
	
	queryPage : function(){
		_this = this;
		var params = {
			itemnoFuzzy : $("#itemno").val(),
			itemnameFuzzy : $("#itemname").val(),
			docketstatus : $("#docketstatus").val(),
			reqTimeStart : $("#reqTimeStart").val(),
			reqTimeEnd : $("#reqTimeEnd").val(),
			gcode : $("#gcode").val()
		}
		if(!!_this.page){
			_this.page.page("remote",0,params);
		}else{
			params = _this.createInitParams(params);
			_this.page = $("#page").page({
				pageSize : 10,
				currentPageIndex:_this.currentPageNo,
				remote: {
					url: _this.urlItems.queryByPageURL,
			        params: params, 
			        success: function (data, pageIndex) {
			        	if(data.code==_this.successCode){
			        		var pageResult = data.result;
			        		if(pageResult.itemList.length>0){
			        			for(var index in pageResult.itemList){
			        				var element = pageResult.itemList[index];
			        				element["seqNum"]=parseInt(pageResult.pageSize)*(parseInt(pageResult.pageNo)-1)+parseInt(index)+1;
			        			}
			        			$("#page_grid").html($("#dataTmp").render(pageResult.itemList));
			        			_this.curGoodItemList = pageResult.itemList;
			        		}else{
			        			$("#page_grid").html('<tr><td align="center" colspan="11">暂无数据</td></tr>');
			        			_this.curGoodItemList = pageResult.itemList;
			        		}
			        		_this.storeQueryParmas(pageIndex);
			        		_this.isFirst = false;
			        	}else{
			        		  webDialogUtil.simpleAlert(data.msg, "温馨提示"); 
			        	}
			        },
			        error : function(){
			        	webDialogUtil.simpleAlert("数据查询异常，请联系开发人员", "温馨提示"); 
			        }
				},
				firstBtnText : '首页',
				lastBtnText : '尾页',
				prevBtnText : '上一页',
				nextBtnText : '下一页',
				showInfo : true,
				showJump : true,
				jumpBtnText : '跳转',
				pageSizeItems: [10,20,50,100,200],
				showPageSizes : true,
				infoFormat : '共{pageCount}页,{total}项'
			});
		}
	},
	queryGoodsPage : function(){
		_this = this;
		var params = {
			gcode : $("#gcodeFilter").val(),
			gname : $("#gnameFilter").val()
		}
		if(!!_this.hgPage){
			_this.hgPage.page("remote",0,params);
		}else{
			_this.hgPage = $("#page_goods").page({
				pageSize : 5,
				remote: {
					url: _this.urlItems.queryHgGoodsByPageURL,
			        params: params, 
			        success: function (data, pageIndex) {
			        	if(data.code==_this.successCode){
			        		var pageResult = data.result;
			        		_this.hgGoods = pageResult.itemList;
			        		if(pageResult == null || pageResult.itemList == null || pageResult.itemList.length==0){
			        			$("#data_grid_goods").html('<tr><td align="center" colspan="11">暂无数据</td></tr>');
			        		}else{
			        			$("#data_grid_goods").html($("#dataTmp_goods").render(pageResult.itemList));
			        		}
			        	}else{
			        		 webDialogUtil.simpleAlert(data.msg, "温馨提示"); 
			        	}
			        },
			        error : function(){
			        	 webDialogUtil.simpleAlert("数据查询异常，请联系开发人员", "温馨提示"); 
			        }
				},
				firstBtnText : '首页',
				lastBtnText : '尾页',
				prevBtnText : '上一页',
				nextBtnText : '下一页',
				showInfo : true,
				showJump : true,
				jumpBtnText : '跳转',
				showPageSizes : true,
				infoFormat : '共{pageCount}页'
			});
		}
	},
	/**
	 * 联动选择海关商品信息
	 */
	selGcode : function(gcode){
		$("input[name='gcode']").val(gcode);
		$("#choose_goods_modal").modal('hide'); 
	},
	queryHisPage : function(id){
		_this = this;
		var params = {
			id :id
		}
		if(!!_this.hisPage){
			_this.hisPage.page("remote",0,params);
		}else{
			_this.hisPage = $("#history_page").page({
				pageSize : 5,
				remote: {
					url: _this.urlItems.queryByHisPageURL,
			        params: params, 
			        success: function (data, pageIndex) {
			        	if(data.code==_this.successCode){
			        		var pageResult = data.result;
			        		if(pageResult.itemList.length>0){
			        			for(var index in pageResult.itemList){
			        				var element = pageResult.itemList[index];
			        				element["seqNum"]=parseInt(pageResult.pageSize)*(parseInt(pageResult.pageNo)-1)+parseInt(index)+1;
			        			}
			        			$("#his_page_grid").html($("#hisDataTmp").render(pageResult.itemList));
			        		}else{
			        			$("#his_page_grid").html('<tr><td align="center" colspan="11">暂无数据</td></tr>');
			        		}
			        	}else{
			        		webDialogUtil.simpleAlert(data.msg, "温馨提示"); 
			        	}
			        },
			        error : function(){
			        	webDialogUtil.simpleAlert("数据查询异常，请联系开发人员", "温馨提示"); 
			        }
				},
				firstBtnText : '首页',
				lastBtnText : '尾页',
				prevBtnText : '上一页',
				nextBtnText : '下一页',
				showInfo : true,
				showJump : true,
				jumpBtnText : '跳转',
				showPageSizes : true,
				infoFormat : '共{pageCount}页,{total}项'
			});
			_this.hisId = id;
		}
	},
	//记录当前页数据，再删除一条数据后局部刷新页面
	curGoodItemList: null,
	//数据删除成功后遍历当前页面的数据，将删除成功的数据从数组中去除，然后重新渲染页面
	delGoodsForPage: function(id){
		for(var i = 0;i < this.curGoodItemList.length;i ++){
			if(this.curGoodItemList[i].id == id){
				this.curGoodItemList.splice(i,1);
			}
		}
		$("#page_grid").html($("#dataTmp").render(this.curGoodItemList));
	},
	delGoods : function(id){
		  webDialogUtil.simpleConfrimAlert('是否确认删除?', function(){
		    	$.ajax({
					url:_this.urlItems.delGoodsRUL,
					data:{id:id},//JSON.stringify(docket),
					dataType:'json',
					type:'post',
					success:function(data){
						if(data.code!=10000){
							window.webDialogUtil.toast({
								text: data.msg,
								title: '温馨提示'
							});
							//webDialogUtil.simpleAlert(data.msg, "温馨提示"); 
						}else{
							_this.delGoodsForPage(id);
							window.webDialogUtil.toast({
								type: 'success',
								title: '操作成功'
							});
							//_this.queryPage();
						}
					},
					error:function(){
						webDialogUtil.simpleAlert("删除出现异常,请联系开发人员", "温馨提示"); 
					}
				});
		});
	},
	queryCusPage : function(){
		_this = this;
		var params = {
			docketCode : $("#customercodeFilter").val(),
			docketName : $("#customernameFilter").val()
		}
		
		if(!!_this.cusPage){
			_this.cusPage.page("remote",0,params);
		}else{
			_this.cusPage = $("#customer_page").page({
				pageSize : 5,
				remote: {
					url: _this.urlItems.queryCustomerByPageURL,
			        params: params, 
			        success: function (data, pageIndex) {
			        	if(data.code==_this.successCode){
			        		var pageResult = data.result;
			        		if(pageResult == null || pageResult.itemList == null || pageResult.itemList.length==0){
			        			$("#customer_data_grid").html('<tr><td align="center" colspan="11">暂无数据</td></tr>');
			        		}else{
			        			$("#customer_data_grid").html($("#cusDataTmp").render(pageResult.itemList));
			        		}
			        	}else{
			        		 webDialogUtil.simpleAlert(data.msg, "温馨提示"); 
			        	}
			        },
			        error : function(){
			        	webDialogUtil.simpleAlert("数据查询异常,请联系开发人员", "温馨提示"); 
			        }
				},
				firstBtnText : '首页',
				lastBtnText : '尾页',
				prevBtnText : '上一页',
				nextBtnText : '下一页',
				showInfo : true,
				showJump : true,
				jumpBtnText : '跳转',
				showPageSizes : true,
				infoFormat : '共{pageCount}页'
			});
		}
	},
	selCustomer : function(value){
		$("#customercode").val(value);
		$("#choose_customer_modal").modal('hide'); 
	},
	queryHistory : function(id){
		_this.queryHisPage(id);
		$("#choose_history_modal").modal('show'); 
	},
	createInitParams : function(params){
		if(!!historyBackParams){
			_this.currentPageNo = historyBackParams.selectPageNo;
			delete historyBackParams.selectPageNo;
			$("#itemno").val(historyBackParams.itemno),
			$("#itemname").val(historyBackParams.itemname),
			$("#docketstatus").val(historyBackParams.docketstatus);
			return historyBackParams;
		}else{
			return params;
		}
	},
	storeQueryParmas : function(pageNo){
		var params = {
				itemno : $("#itemno").val(),
				itemname : $("#itemname").val(),
				docketstatus : $("#docketstatus").val()
			}
		params['selectPageNo']=pageNo;
		var jsonObjStr = JSON.stringify(params);
		goodsStatsCtrl.setCookie(cookieHistoryBackParamsName, jsonObjStr,1,"/");
	},
	
	ajaxDownload : function(){
		var params = {
			itemnoFuzzy : $("#itemno").val(),
			itemnameFuzzy : $("#itemname").val(),
			docketstatus : $("#docketstatus").val(),
			reqTimeStart : $("#reqTimeStart").val(),
			reqTimeEnd : $("#reqTimeEnd").val(),
			gcode : $("#gcode").val()
		}
		$.ajax({
			url:basePath+"/nt/packageForstats/goodsStats/exportGoodsExcel",
			data:params,
			type:'post',
			cache:false,
			success:function(data) {
				if(data.success){
					var url = basePath+"/nt/transData/download?fileName="+data.fileName;
					$("body").append("<iframe id='file_download_frame' src='" + url +"' frameborder=0 width=0 height=0 style='display:none'></iframe>");
				}else{
					window.webDialogUtil.alert("提示",data.errMsg);
				}
			},
			error : function() {
				window.webDialogUtil.alert("提示","操作失败");
			}
		});
	},
	importData:function (){
		var _this = this;
		var params = [];
		$("input").each(function(){
			if(!!$(this).val() && !!$(this).attr("id")){
				var param = {name:'',value:''};
				param.name=$(this).attr("id");
				param.value=$(this).val();
				params.push(param);
			}
		});
		webDialogUtil.simpleConfrimAlert("是否确认提交", function(){
			//基于ajaxfileUpload.js实现
			$.ajaxFileUpload({
				url : _this.urlItems.importDataURL,
				secureuri : false,
				fileElementId : 'excelFile',//file标签的id
				dataType : 'json',
				data : params,
				success: function (data, status) {
					//存在未导入成功的备案数据，可以下载
					console.log(data);
					console.log(data.code);
					console.log(typeof data.code);
					if(data.code=='2'){
						webDialogUtil.simpleConfrimAlert("存在没有智能备案成功的商品信息，请确认", function(){_this.downLoadErroGoods(data.msg);});
					}
					else {
						webDialogUtil.simpleAlert(data.msg, "温馨提示", null, 300, 10);
					}
				},
				error: function (data, status, e) {
					webDialogUtil.simpleAlert("处理异常", "温馨提示");
				}
			});
		});

	},
	//下载未能成功备案的商品@ps
	downLoadErroGoods :function (str) {
		var _this = this;
		var data ={"itemName":str};
		$.ajax({
			type: "POST",
			url: goodsStatsCtrl.goodsStats.urlItems.exportErrorGoodsExcel,
			data: data,
			success: function(data){
				if(data.success) {
				$("body").append("<iframe id='downLoadErroGoods' src='" +goodsStatsCtrl.goodsStats.urlItems.downLoadURLWithRealPath+'?fileName='+ data.fileName +"' frameborder=0 width=0 height=0 style='display:none'></iframe>");
				}
			}
		});
	},
	downloadTemplate: function(fileName){

		_this = this;

		var url = _this.urlItems.downLoadURL+"?fileName="+fileName;

		var iframeId = "big_tmpfile_download_frame" ;
		if(fileName == 'template-small-pkg.xls'){
			iframeId =  "small_tmpfile_download_frame";
		}

		$("body").append("<iframe id='"+iframeId+"' src='" + url +"' frameborder=0 width=0 height=0 style='display:none'></iframe>");
	},
	//选择当前页
	selectCurPage: function(){
		$('[name=chkItem]:checkbox').attr('checked',true);
	},
	//批量提交备案
	batchSubmit: function(){
		var ids = "";
		$('input:checkbox[name=chkItem]:checked').each(function(i){
			ids += this.id+',';
		});
		if(ids.length == 0){
			webDialogUtil.simpleAlert("请选择相应的备案记录", "温馨提示"); 
			return;
		}else{
			ids = ids.substring(0,ids.length-1);
		}
		webDialogUtil.simpleConfrimAlert('是否确认提交?', function(){

			goodsStatsCtrl.goodsStats.loadingDialog = webDialogUtil.loading('处理中...');
			$.ajax({
					url:goodsStatsCtrl.goodsStats.urlItems.batchSubmitGoodsUrl,
					dataType:'json',
					type:'post',
					data: {ids:ids},
					success:function(data){
						goodsStatsCtrl.goodsStats.loadingDialog.close();
						var successRecord = data.success;
						var faildRecord = data.faild;
						webDialogUtil.simpleAlert("成功提交"+successRecord.length+"条商品备案", "温馨提示"); 
						for(var i = 0;i < successRecord.length;i ++){
							$('#'+successRecord[i]).hide();
						}

					},
					error:function(){
						  webDialogUtil.simpleAlert("批量提交备案失败", "温馨提示"); 
					}
				});
		});
		
	},
	loadingDialog: {},
	event : function(){
		_this = this;
		$("#goods_search").on("click",function(){
			_this.queryPage();
		});
		$("#customercode_choose").on("click",function(){
			$("#choose_customer_modal").modal();
			_this.queryCusPage();
		});
		$("#custom_serach").on("click",function(){
			_this.queryCusPage();
		});
	
		$("#custom_reset").on("click",function(){
			$("input[name='customercodeFilter']").val("");
			$("input[name='customernameFilter']").val("");
		});
		$("#goods_choose").on("click",function(){
			$("#choose_goods_modal").modal();
			_this.queryGoodsPage();
		});
		$("#goods_modal_search").on("click",function(){
			_this.queryGoodsPage();
		});
		$("#goods_modal_reset").on("click",function(){
			$("input[name='gcodeFilter']").val("");
			$("input[name='gnameFilter']").val("");
		});
		$("#downloadButton2").on("click", function(){
			_this.downloadTemplate('template-goods.xls');
		});
		
		$("#exportButton").on("click",function(){
			goodsStatsCtrl.goodsStats.ajaxDownload();
		});
		$("#importButton").on("click",function(){
			_this.importData();
		});
	},
	viewDetail : function(){
		
	}
};
$(function(){
	goodsStatsCtrl.goodsStats.event();
	goodsStatsCtrl.goodsStats.queryPage();
});
